<!DOCTYPE html>
<html>
<head>
    <title>双乾投标跳转中...</title>
    <meta http-equiv="content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div>双乾页面跳转中...,请您不要关闭页面</div>
<script type="text/javascript">
    (function(root, factory) {
        window.onerror = function(){
            return true;
        };
        if (typeof define === 'function' && define.amd) {
// AMD
            define(function(require, exports, module) {
                var $ = require("jquery");
                var _ = require("underscore");
                return factory($, window);
            });
        } else {
            root.OEM = factory(root.jQuery, window);
        }
    }(this, function($, w) {
        'use strict';
        /**
         * 工具方法
         */
        var utils = {
                queryUri: function(search) {
                    var s = search || location.search,
                        str = s && /^\?/.test(s) ? s.slice(1) : s,
                        r = {},
                        kvs = str.split("&");
                    if(!str){
                        return false;
                    }
                    for (var i = 0, len = kvs.length; i < len; i++) {
                        var kv = kvs[i].split("=");
                        r[kv[0]] = kv[1];
                    }
                    return r;
                },
                getIEVersion: function(){
                    var rv = -1;
                    if (navigator.appName == 'Microsoft Internet Explorer') {
                        var ua = navigator.userAgent;
                        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
                        if (re.exec(ua) != null)
                            rv = parseFloat(RegExp.$1);
                    }
                    return rv;
                }
            },
            oemCustom,
            oemMessage,
            oemNotification;

        /**
         * 获取消息
         */
        function Message(){
            /**
             * {
*     important       标红
*     type            消息类型
*     time            时间
*     websiteUrl
*     showIcon        显示浏览器图标
*     showImgIcon     显示图片图标
*     iconName        图标名称
*     imgName         图片图标名称
*     content         详细内容
*     country         国家名称
*     prefix          前值
*     expected        预期值
*     published       公布值
*     star            分数
*     evaluate        评价
* }
             * @type {Array}
             */
            this.template = [
                '<li id="<%= id %>" class="oem-list_item<% if(important) {%> s-important<% } %><% if(type == 1) {%> oem-list_data<% } %>">',
                '<div class="oem-content_h">',
                '<i class="oem-content_icon"></i>',
                '<span class="oem-content_date"><%=time%></span>',
                '</div>',
                '<div class="oem-content_b">',
                '<% if(type != 1) { %>',
                '<div class="oem-content_attach">',
                '<% if(showWebsiteIcon) {%>',
                '<a href="<%= websiteUrl %>" target="_blank"><img src="//cdn.jin10.com/oem/images/website2.png"></a>',
                '<% } %>',
                '<% if(showVideoIcon) {%>',
                '<a href="<%= videoUrl %>" target="_blank"><img src="//cdn.jin10.com/oem/images/video2.png"></a>',
                '<% } %>',
                '<% if(showImgIcon) {%>',
                '<a href="//image.jin10.com/<%= imgUrl %>" target="_blank"><img src="//image.jin10.com/<%= imgName %>"></a>',
                '<% } %>',
                '</div>',
                '<p class="oem-content_text">',
                '<%= content %>',
                '</p>',
                '<% } else { %>',
                '<div class="oem-content_data">',
                '<div class="oem-content_data-img">',
                '<img src="//cdn.jin10.com/oem/images/flag/<%= country %>.png" width="40" height="40">',
                '</div>',
                '<div class="oem-content_data-text">',
                '<p><%= content %></p>',
                '<p>前值：<%= prefix %> 预期：<%= expected %></p>',
                '</div>',
                '</div>',
                '<div class="oem-content_data-info">',
                '<p><img src="//cdn.jin10.com/oem/images/star/<%= star %>.png" width="20" height="34"></p>',
                '<p class="oem-content_data-published">公布：<%= published %></p>',
                '<p><img src="//cdn.jin10.com/oem/images/updown/<%= evaluate %>.png" width="82" height="24"></p>',
                '</div>',
                '<% } %>',
                '</div>',
                '</li>'
            ].join('');
            this.$dom = $('#J_list');
            this.$more = $('#J_moreTips');
            this.lastMsgId = 0;
            this.scrollEnd = false;
            this.loaded = false;
        }
        $.extend(Message.prototype, {
            /**
             * 向服务器获取数据
             */
            getDatas: function(params){
                var self = this;
                this.loaded = true;
                this.$more.show();
                var dtd = $.Deferred();
                $.ajax({
                    url: '//m.jin10.com/flash',
                    data: params || {
                        maxId: self.lastMsgId,
                        count: oemCustom.defaults.messageNum
                    },
                    dataType: 'jsonp',
                    jsonp: 'jsonpCallback',
                    success: function(json){
                        self.$more.hide();
                        dtd.resolve(json);
                    },
                    complete: function(){

                    },
                    error: function(e){
                        self.$more.hide();
                        dtd.reject(e);
                    }
                })
                return dtd;
            },
            /**
             * 过滤数据
             * @param    {Arrray}   要过滤的数据
             * @return   {Object}   根据类型返回过滤后的对象
             */
            filterData: function(data){
                data = data.split('#');
                var type = data[0],
                    time,
                    content,
                    important,
                    star = 0,
                    websiteUrl = '',
                    videoUrl = '',
                    id,
                    imgIcon,
                    prefix = 0,
                    expected = 0,
                    published = 0,
                    country,
                    evaluate,
                    params = {};

                if(type == 1){
                    time = data[8].split(' ')[1];
                    content = data[2];
                    star = data[6];
                    important = star > 3 ? true : false;
                    id = data[12];
                    prefix = data[3];
                    expected = data[4];
                    published = data[5];
                    country = data[9];
                    evaluate = data[7];
                    params = {
                        id: id,
                        important: important,
                        type: 1,
                        time: time,
                        content: content,
                        country: country,
                        prefix: prefix,
                        expected: expected,
                        published: published,
                        star: star,
                        evaluate: star >= 3 ? evaluate : evaluate + '2'
                    };
                }else{
                    time = data[2].split(' ')[1];
                    content = data[3];
                    important = data[1] == 0 ? true : false;
                    id = data[11];
                    websiteUrl = data[4];
                    imgIcon = data[6];
                    videoUrl = data[5];
                    if(id == '20160926143732319100'){
                        content = content.replace('<b>', '');
                    }
                    params = {
                        id: id,
                        important: important,
                        type: 0,
                        time: time,
                        content: content,
                        websiteUrl: websiteUrl,
                        showWebsiteIcon: websiteUrl ? true : false,
                        videoUrl: videoUrl,
                        showVideoIcon: videoUrl ? true : false,
                        showImgIcon: imgIcon ? true : false,
                        imgName: imgIcon,
                        imgUrl: imgIcon.replace('_lite', '')
                    };
                }
                return params;
            },
            /**
             * 渲染
             */
            render: function(isSocket, messages){
                var self = this;
                var dtd = $.Deferred();
                // 通过socket获取
                if(typeof isSocket !== 'undefined' && isSocket){
                    var msg = self.filterData(messages);
                    var html = _.template(self.template)(msg);
                    self.$dom.prepend(html);
                    oemNotification.sound.play();
                    if(!msg.important){
                        return false;
                    }
                    // 通知
                    var notificationTitle = '金十数据 - www.jin10.com',
                        notificationOptions = {
                            timeout: 8000,
                            onClick: function(){
                                w.focus();
                                this.close();
                            }
                        }
                    if(msg.type == 0){
                        notificationOptions.icon = msg.imgName ? '//image.jin10.com/' + msg.imgName : '//cdn.jin10.com/oem/images/tongzhi.png';
                        notificationOptions.body = msg.content.replace(/<br \/>/ig,"\n").replace(/<[^>]+>/g,"");
                    }else{
                        notificationOptions.icon = '//cdn.jin10.com/oem/images/flag/'+ msg.country +'.png';
                        notificationOptions.body = msg.time + ' ' + msg.country + msg.content + '\n前值：'+ msg.prefix + ' 预期：' + msg.expected + ' 实际：'+ msg.published +'\n解读：理论上较为【'+ msg.evaluate +'】金银价格';
                    }
                    oemNotification.create(notificationTitle, notificationOptions);
                    return false;
                }
                // 通过ajax获取
                this.getDatas().done(function(datas){
                    var html = '';
                    $.each(datas, function(i, data){
                        html += _.template(self.template)(self.filterData(data));
                    });
                    self.$dom.append(html);
                    self.lastMsgId = self.$dom.find('li').last().attr('id');
                    self.loaded = false;
                    self.scrollEnd = false;
                    dtd.resolve();
                }).fail(function(e){
                    self.loaded = false;
                    self.scrollEnd = false;
                });
                return dtd;
            },
            bindEvent: function(){
                var self = this;
                var bottomOffset = 10;
                var $win = $(w);
                var getMore = true;
                var timer;
                $win.scroll(function () {
                    if(timer){
                        clearTimeout(timer);
                    }
                    timer = setTimeout(function(){
                        if(self.loaded || self.scrollEnd){
                            return false;
                        }
                        //当前窗口的高度
                        var windowHeight = $win.height();
                        //当前滚动条从上往下滚动的距离
                        var scrollTop = $win.scrollTop();
                        //当前文档的高度
                        var docHeight = $(document).height();

                        //当 滚动条距底部的距离 + 滚动条滚动的距离 >= 文档的高度 - 窗口的高度
                        if ((bottomOffset + scrollTop) >= docHeight - windowHeight) {
                            self.scrollEnd = true;
                            self.render();
                        }
                    }, 200);

                });
            },
            init: function(){
                var self = this;
                oemNotification = new OEMNotification();
                oemNotification.init();
                this.render().done(function(){
                    self.bindEvent();

                    SocketIo.getScript().done(function(){
                        new SocketIo().connect(function(data){
                            self.render(true, data);
                        });
                    })
                });
                return this;
            }
        });

        /**
         * socket连接
         */
        function SocketIo(){
            this.bid = false;
            this.socket = null;
            // 重连初始次数
            this.reconnectCount = 0;
            // 重连最大次数
            this.maxReconnectNum = 8;
            // 重连时间
            this.reconnectTime = 5;
        }
        /**
         * 静态方法，获取socketjs和serverjs
         */
        SocketIo.getScript = function(){
            var dtd = $.Deferred();
            var socketIoUrl = '//cdn.jin10.com/connect-io/socket.io.js?20160926',
                serverUrl = '//www.jin10.com/js/server.js?rnd=' + Math.random();
            $.getScript(serverUrl).done(function(){
                $.getScript(socketIoUrl).done(function(){
                    dtd.resolve();
                });
            });
            return dtd;

        };
        $.extend(SocketIo.prototype, {
            /**
             * 重新获取服务器
             */
            reGetServer: function(){
                if(this.reconnectCount >= this.maxReconnectNum){
                    return false;
                }
                this.reconnectCount++;
                var self = this;
                setTimeout(function(){
                    self.getServer();
                }, this.reconnectTime * 1000);
            },
            /**
             * 获取服务器
             */
            getServer: function(){
                var self = this;
                $.ajax({
                    dataType: "script",
                    url: "//www.jin10.com/js/server.js?rnd=" + Math.random(),
                    success: function () {
                        self.reconnectCount = 0;
                        self.bid = true;
                        self.socket.disconnect();
                        self.socket = null;
                        setTimeout(function () {
                            self.connect(function(data){
                                oemMessage.render(true, data);
                            });
                        }, 1);
                    },
                    error: function () {
                        setTimeout(function () {
                            self.reGetServer();
                        }, 1000);
                    }
                });
            },
            /**
             * 建立连接
             */
            connect: function(callback){
                // 如果没有服务器列表则不连接
                if(typeof serverArr === 'undefined' || !serverArr.length){
                    return false;
                }
                var self = this;
                var n = Math.floor(Math.random() * serverArr.length + 1) - 1;
                var serverUrl = serverArr[n];
                this.socket = io.connect(serverUrl, {'force new connection': true, 'reconnection': false});
                this.socket.on('user message', function (msg) {
                    callback(msg);
                    // console.log('connect done');
                });
                this.socket.on('connect', function () {
                    self.bid = false;
                    self.socket.emit('reg', "ok");
                });
                this.socket.on('error', function (reason) {
                    // console.log('error');
                    self.reGetServer();
                });

                this.socket.on('connect_error', function (reason) {
                    // console.log('connect_error');
                    self.reGetServer();
                });
                this.socket.on('repair', function (reason) {
                    // console.log('repair');
                    self.reGetServer();
                });
                this.socket.on('reconnecting', function (nextRetry) {
                    // console.log('reconnecting');
                    if (nextRetry > self.maxReconnectNum) {
                        this.socket.reconnecting = null;
                        this.socket = null;
                        io = null;
                    }
                });
                this.socket.on('disconnect', function () {
                    // console.log('disconnect');
                    if (!self.bid) {
                        self.reGetServer();
                    }
                });
            }
        });

        /**
         * 消息通知
         */
        function oemPush(){
            var
                hasPermission = false,
                notifications = {}, // map
                currentId = 0,
                /**
                 * 检测用户的浏览器是否支持通知
                 */
                isSupported = (function(){
                    var isSupported = false;
                    try {

                        isSupported =

                            /* Safari, Chrome */
                            !!(w.Notification ||

                                /* Chrome & ff-html5notifications plugin */
                                w.webkitNotifications ||

                                /* Firefox Mobile */
                                navigator.mozNotification ||

                                /* IE9+ */
                                (w.external && w.external.msIsSiteMode() !== undefined));

                    } catch (e) {}

                    return isSupported;

                })(),
                /**
                 * 关闭一个通知
                 */
                closeNotification = function(id){
                    var errored = false,
                        notification = notifications[id];
                    if(typeof notification !== 'undefined'){
                        // Safari 6+, Chrome 23+
                        if(notification.close){
                            notification.close();
                        }
                        // webkit
                        else if(notification.cancel){
                            notification.cancel();
                        }
                        // IE9 +
                        else if(w.external && w.external.msIsSiteMode){
                            w.external.msSiteModeClearIconOverlay();
                        }else{
                            errored = true;
                            alert('');
                        }
                        if(!errored){
                            return removeNotification(id);
                        }
                    }
                    return false;
                },
                addNotification = function(notification){
                    var id = currentId;
                    notifications[id] = notification;
                    currentId++;
                    return id;
                },
                // 删除notifications里对应的id
                removeNotification = function(id){
                    var dict = {},
                        success = false,
                        key;
                    for(key in notifications){
                        if(notifications.hasOwnProperty(key)){
                            if(key != id){
                                dict[key] = notifications[key];
                            }else{
                                success = true;
                            }
                        }
                    }
                    notifications = dict;
                    return success;
                },
                createCallback = function(title, options){
                    var notification,
                        wrapper,
                        id,
                        onClose;
                    options = options || {};
                    // Safari 6+, Firefox 22+, Chrome 22+, Opera 25+
                    if(w.Notification){
                        notification = new w.Notification(
                            title,
                            {
                                icon: options.icon || '',
                                body: options.body,
                                tag: options.tag,
                                requireInteraction: options.requireInteraction
                            }
                        );
                    }
                    // webkit
                    else if(w.webkitNotifications){
                        notification = w.webkitNotifications.createNotification(
                            options.icon,
                            title,
                            options.body
                        );
                        notification.show();
                    }
                    // firefox
                    else if(navigator.mozNotification){
                        notification = navigator.mozNotification.createNotification(
                            title,
                            options.body,
                            options.icon
                        );
                        notification.show();
                    }
                    // ie9+
                    else if(w.external && w.external.msIsSiteMode()){
                        w.external.msSiteModeClearIconOverlay();
                        w.external.msSiteModeSetIconOverlay(
                            ((isString(options.icon) || isUndefined(options.icon))
                                ? options.icon
                                : options.icon.x16), title
                        );
                        w.external.msSiteModeActivate();
                        notification = {};
                    }
                    else{
                        throw new Error('Unable to create notification: unknown interface');
                    }

                    id = addNotification(notification);

                    wrapper = {
                        get: function () {
                            return notification;
                        },

                        close: function () {
                            closeNotification(id);
                        }
                    };

                    if (options.timeout) {
                        setTimeout(function () {
                            wrapper.close();
                        }, options.timeout);
                    }

                    // 回调事件
                    if(_.isFunction(options.onShow)){
                        notification.addEventListener('show', options.onShow);
                    }
                    if(_.isFunction(options.onError)){
                        notification.addEventListener('error', options.onError);
                    }
                    if(_.isFunction(options.onClick)){
                        notification.addEventListener('click', options.onClick);
                    }

                    onClose = function(){
                        removeNotification(id);
                        if(_.isFunction(options.onClose)){
                            options.onClose.call(this);
                        }
                    }

                    notification.addEventListener('close', onClose);
                    notification.addEventListener('cancel', onClose);

                    return wrapper;
                },

                Permission = {
                    DEFAULT: 'default',
                    GRANTED: 'granted',
                    DENIED: 'denied',
                    // 请求许可
                    request: function(onGranted, onDenied){
                        if(!isSupported){
                            return false;
                        }
                        var self = this,
                            callback = function(result){
                                switch (result) {
                                    case self.GRANTED:
                                        hasPermission = true;
                                        if (onGranted) onGranted();
                                        break;

                                    case self.DENIED:
                                        hasPermission = false;
                                        if (onDenied) onDenied();
                                        break;

                                }
                            };
                        /* Safari 6+, Chrome 23+ */
                        if (w.Notification && w.Notification.requestPermission) {
                            Notification.requestPermission(callback);
                        }
                        /* webkit */
                        else if (w.webkitNotifications && w.webkitNotifications.checkPermission) {
                            w.webkitNotifications.requestPermission(callback);
                        }
                    },
                    // 返回按是已经请求许可
                    has: function(){
                        return hasPermission;
                    },
                    // 返回是否已经授权
                    get: function(){
                        var permission;

                        if (!isSupported) {
                            return false;
                        }

                        /* Safari 6+, Chrome 23+ */
                        if (w.Notification && w.Notification.permissionLevel) {
                            permission = w.Notification.permissionLevel;

                            /* Legacy webkit browsers */
                        } else if (w.webkitNotifications && w.webkitNotifications.checkPermission) {
                            permission = Permissions[w.webkitNotifications.checkPermission()];

                            /* Firefox 23+ */
                        } else if (w.Notification && w.Notification.permission) {
                            permission = w.Notification.permission;

                            /* Firefox Mobile */
                        } else if (navigator.mozNotification) {
                            permission = Permissions.GRANTED;

                            /* IE9+ */
                        } else if (w.external && w.external.msIsSiteMode() !== undefined) {
                            permission = w.external.msIsSiteMode() ? Permission.GRANTED : Permission.DEFAULT;
                        } else {
                            return false;
                        }

                        return permission;
                    }

                },

                Permissions = [Permission.GRANTED, Permission.DEFAULT, Permission.DENIED];

            return {
                notifications: notifications,
                Permission: Permission,
                isSupported: isSupported,
                createCallback: createCallback,
                closeNotification: closeNotification,
                addNotification: addNotification,
                removeNotification: removeNotification
            }
        }
        function OEMNotification(){
            this.push = oemPush();
            this.$soundInput = $('#J_ctrl_sound');
            this.$notificationInput = $('#J_ctrl_notification');
            this.$checkboxWrap = $('.J_checkboxWrap');
        }
        $.extend(OEMNotification.prototype, {
            // 声音
            sound: (function(){
                var browserVer = utils.getIEVersion(),
                    bgm,
                    src = '//cdn.jin10.com/oem/images/notice.wav';
                if (browserVer > -1 && browserVer < 9) {
                    $('body').append('<embed id="J_audiotagIE" src="'+ src +'" autostart="false" loop="false" width="0" height="0"></embed>');
                    bgm = document.getElementById('J_audiotagIE');
                } else {
                    bgm = new Audio();
                    bgm.src = src;
                    bgm.loop = false;
                }

                return {
                    play: function(){
                        if(!$('#J_ctrl_sound').prop('checked')){
                            return false;
                        }
                        // bgm.loop = typeof loop !== 'undefined' ? loop : false;
                        bgm.play();
                    },
                    pause: function(){
                        bgm.pause();
                    }
                }
            })(),
            // 创建一个新的通知
            create: function(title, options){
                var self = this;
                if(!this.push.isSupported || !this.$notificationInput.prop('checked')){
                    return false;
                }
                if(!this.push.Permission.has()){
                    this.push.Permission.request(function(){
                        self.push.createCallback(title, options);
                    })
                }else{
                    this.push.createCallback(title, options);
                }
            },
            // 关闭通知
            close: function(tag){
                var key, notification, self = this;
                for(key in this.push.notifications){
                    notification = this.push.notifications[key];
                    if(notification.tag === tag){
                        return self.push.closeNotification(key);
                    }
                }
            },
            bindEvent: function(){
                var self = this;
                this.$notificationInput.on('change', function(){
                    if(!self.push.isSupported){
                        return false;
                    }
                    if(!self.push.Permission.has() && $(this).prop('checked')){
                        self.push.Permission.request();
                    }
                });
                this.$checkboxWrap.on('click', '.J_checkbox', function(){
                    var _this = $(this),
                        $input = _this.siblings('input');
                    if(_this.attr('data-type') === 'notification'){
                        if(!self.push.isSupported){
                            alert('您当前浏览器不支持该功能\n建议使用谷歌、火狐等高级浏览器');
                            return false;
                        }
                    }
                    _this.toggleClass('check');
                    $input.trigger('click');
                });
                // 默认进入页面检查浏览器的通知设置
                if(this.push.Permission.get() === this.push.Permission.GRANTED){
                    this.$notificationInput.siblings('.J_checkbox').trigger('click');
                }
            },
            init: function(){
                this.bindEvent();
                return this;
            }
        });

        /**
         * 自定义皮肤、字体
         */
        function Custom(){
            this.defaults = {
                color: '333',
                backgroundColor: 'fff',
                fontSize: '13px',
                messageNum: 200
            };
            this.$wrap = $('#J_oem');
            var params = utils.queryUri();
            $.extend(this.defaults, params);
            this.setting();
        }
        $.extend(Custom.prototype, {
            getKey: function(key){
                return this.defaults[key];
            },
            setting: function(){
                var self = this;
                var theme = this.defaults.theme;
                if(typeof theme !== 'undefined' && theme){
                    this.$wrap.addClass('theme-' + theme);
                }
                this.$wrap.css({
                    color: '#' + self.defaults.color,
                    backgroundColor: '#' + self.defaults.backgroundColor,
                    fontSize: self.defaults.fontSize
                });
            }
        });

        oemCustom = new Custom();
        oemMessage = new Message().init();
        return oemMessage;
    }));
</script>

</body>
</html>
